const RoleModel = require("../model/roles");
// 导入需要的验证规则对象
const {
  get_role_list_schema,
  add_role_schema,
  edit_role_schema,
  delete_role_schema,
  get_role_schema,
} = require("../schema/role");

// 添加角色接口
exports.addRole = (req, res) => {
  const { value, error } = add_role_schema.validate(req.body);
  if (error) throw error;
  RoleModel.create(value).then(function (role) {
    if (!role) {
      return res.send({
        code: 1,
        message: "创建失败",
        data: null,
      });
    }
    return res.send({
      code: 0,
      message: "创建成功",
      data: role,
    });
  });
};
// 删除角色接口
exports.deleteRole = (req, res) => {
  const { value, error } = delete_role_schema.validate(req.body);
  if (error) throw error;
  const role_ids = value.role_ids;
  // 对应角色id数组进行删除
  RoleModel.delRole(role_ids || []).then(function (role) {
    if (role !== true) {
      return res.send({
        code: 1,
        message: "删除失败",
        data: null,
      });
    }
    return res.send({
      code: 0,
      message: "删除成功",
      data: role,
    });
  });
};
// 获取角色资源的方法
exports.getRoleResource = (req, res) => {
  const role_id = req.query.role_id;
  RoleModel.getResource(role_id).then((resource) => {
    if (!resource) {
      return res.send({
        code: 1,
        message: "获取角色权限失败",
        data: null,
      });
    }
    return res.send({
      code: 0,
      message: "获取角色权限成功",
      data: resource,
    });
  });
};
// 分配角色资源路由回调函数
exports.updateRoleResource = (req, res) => {
  const role_id = req.query.role_id;
  const data = req.body;
  const all_ids = data.all_ids ?? data.menu_ids.concat(data.permIds);
  RoleModel.updateResource(role_id, all_ids).then((resource) => {
    if (resource !== true) {
      return res.send({
        code: 1,
        message: "修改失败",
        data: null,
      });
    }
    return res.send({
      code: 0,
      message: "修改成功",
      data: resource,
    });
  });
};
